package com.mysite.seckill.web.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.mysite.seckill.commons.common.Constant;
import com.mysite.seckill.commons.po.User;
import com.mysite.seckill.commons.vo.ResultVo;
import com.mysite.seckill.web.service.UserService;

@Controller
public class LoginController {

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private UserService userService;

    @RequestMapping(value = "", method = RequestMethod.GET)
    public String index(HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute(Constant.CURRENT_USER);
        if (user == null) {
            return "login";
        }
        return "redirect:/activity";
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public ResultVo login(HttpSession session, String username, String password) {
        User user = userService.login(username, password);
        session.setAttribute(Constant.CURRENT_USER, user);
        return new ResultVo(user);
    }

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    @ResponseBody
    public ResultVo register(User user) {
        return new ResultVo(userService.addUser(user));
    }
    
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public String logout(HttpServletRequest request, HttpServletResponse response) {
        request.getSession().invalidate();
        return "redirect:";
    }
}
